package com.example.emos.wx.exception;

import com.example.emos.wx.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获参数校验错误
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result paramsExceptionHandle(MethodArgumentNotValidException ex) {
        try {
            List<ObjectError> errors = ex.getBindingResult().getAllErrors();
            String message = errors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(","));
            log.error("参数校验错误: {}", message);
            return Result.error(message);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @ExceptionHandler(EmosException.class)
    public Result emosExceptionHandle(EmosException ex) {
        log.error("发生错误：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result otherExceptionHandle(EmosException ex) {
        log.error("未知异常：{}", ex.getMessage());
        return Result.error("未知错误");
    }
}
